package job;

import java.io.File;
import java.util.Map;

import models.DrCase;

import org.apache.commons.lang.StringUtils;

import play.Play;
import play.jobs.Job;
import play.jobs.On;
import services.CaseService;
import services.SystemParamService;
import utils.BizConstants;
import utils.ShellUtil;
import vos.ResultVo;
import vos.ReturnCode;

/**
 * pcm 转MP3任务
 * @author wangshaoming
 *
 */
@On("0 0 2 * * ? * ")
public class PcmToMp3Job extends Job {
	@Override
	public void doJob(){
		String path=SystemParamService.getValueByCacheId(BizConstants.PARAM_MAP.get("PCM_PATH"));
		if(StringUtils.isEmpty(path)){
			return ;
		}
		//将pcm 转为MP3
		String mp3url=SystemParamService.getValueByCacheId(BizConstants.PARAM_MAP.get("SSH_PCM_TO_MP3_IP"));
		String map3user=SystemParamService.getValueByCacheId(BizConstants.PARAM_MAP.get("SSH_PCM_TO_MP3_USER"));
		String mp3pass=SystemParamService.getValueByCacheId(BizConstants.PARAM_MAP.get("SSH_PCM_TO_MP3_PASS"));
		String mp3Shell=SystemParamService.getValueByCacheId(BizConstants.PARAM_MAP.get("SSH_PCM_TO_MP3_SHELL"));
		if(StringUtils.isEmpty(mp3url)||StringUtils.isEmpty(map3user)||
				StringUtils.isEmpty(mp3pass)||StringUtils.isEmpty(mp3Shell)){
			return;
		}
		File dirFile=new File(path);
		if(!dirFile.isDirectory()){
			return ;
		}
		//遍历pcm路径下的所有文件
		File[] files=dirFile.listFiles();
		for(File file : files){
			String fileName=file.getName();
			String extend=fileName.substring(fileName.lastIndexOf(".")+1, fileName.length());
			if(!"wav".equals(extend)){
				continue;
			}
			String filePath=file.getPath();
			String id=fileName.substring(0,fileName.lastIndexOf(".")-1);
			//生成到新的路径
			String mp3Path=Play.applicationPath.getPath();
			String videoPath=BizConstants.FILE_MP3_PATH+id+".mp3";
			String videoUrl=mp3Path+videoPath;
			
			String shelltext="cd "+mp3Shell+"&& ./PcmToMp3.sh "+
					filePath+" "+videoUrl;
			Map<String,Object> shellMap=ShellUtil.execAndPass(mp3url,map3user,mp3pass,shelltext);
			if(shellMap!=null){
				int shellsta=(int)shellMap.get("status");
				if(shellsta!=0){
					continue;
				}
				//执行成功后将pcm文件删除
				else{
					File mp3File=new File(videoUrl);
					if(mp3File.exists()&&mp3File.length()>0){
						DrCase cases=new DrCase();
						cases.setCaseid(id);
						cases.setVideopath(videoPath);
						boolean issave=CaseService.updateVideoPathById(cases);
						if(issave&&file.exists()){
							file.delete();
						}
					}
					else{
						continue;
					}
				}
			}
		}
	}
}
